package com.cyx.config;

import com.cyx.pojo.User;
import com.cyx.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("doGetAuthorizationInfo 授权");
        //1、这里可以取到getPrincipal
        System.out.println(principalCollection.asList());
        //1、通过获取subject 也可以获取到getPrincipal
        Subject subject = SecurityUtils.getSubject();
        System.out.println(subject);
        System.out.println(subject.getPrincipal());
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        User user = (User) subject.getPrincipal();
        info.addStringPermission(user.getPerms());
//        info.addStringPermission("order:add");
//        info.addStringPermission("order:update");
        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("doGetAuthorizationInfo 认证");

        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        User user = userService.queryUser(token.getUsername());
        if (user == null){
            return null;
        }

        //密码认证 shiro 已实现,principal 可以用来存储用户认证相关信息
        //比如用户涉及到的相关权限都可以放入，在授权处理中可以读取
        return new SimpleAuthenticationInfo(user,user.getPwd(),"");
    }
}
